package com.loe.ui.api

import android.view.View
import android.view.animation.*
import android.webkit.JavascriptInterface
import com.loe.mvp.ext_java.safe
import com.loe.mvp.ext_view.setDelayClickListener
import com.loe.mvp.ext_view.visible
import com.loe.mvp.util.Animator
import com.loe.ui.*
import com.loe.ui.quickjs.UiAnimator
import com.quickjs.JSFunction
import com.quickjs.JSObject

open class ViewApi(private val view: View, val jsObject: JSObject = JSObject(jsContext))
{
    var visible: Boolean
        @JavascriptInterface get() = view.visible
        @JavascriptInterface set(value)
        {
            view.visible = value
        }

    @JavascriptInterface
    fun setOnClickListener(callback: JSFunction)
    {
        view.setOnClickListener { safe { callback.call(jsObject, null) } }
    }

    @JavascriptInterface
    fun setDelayClickListener(callback: JSFunction)
    {
        view.setDelayClickListener() { safe { callback.call(jsObject, null) } }
    }

    @JavascriptInterface
    fun getAnimator(): JSObject
    {
        return UiAnimator(view)
    }

    @JavascriptInterface
    fun setAlpha(alpha: Double)
    {
        view.alpha = alpha.toFloat()
    }

    @JavascriptInterface
    fun performClick()
    {
        view.performClick()
    }

    init
    {
        jsObject.appendJavascriptInterface(this)
        jsObject.key = view.toString()
        jsObject.registerFun("setBg")
        {
            val v = it.get(0)
            if (v is JSObject)
            {
                view.background = v.shape
            } else
            {
                view.bg = v.toString()
            }
        }
    }
}